// 语音识别调试工具
export class VoiceDebugger {
    private static instance: VoiceDebugger;
    private debugMode = false;

    static getInstance(): VoiceDebugger {
        if (!VoiceDebugger.instance) {
            VoiceDebugger.instance = new VoiceDebugger();
        }
        return VoiceDebugger.instance;
    }

    // 启用调试模式
    enableDebug() {
        this.debugMode = true;
        console.log('🔍 语音识别调试模式已启用');
    }

    // 禁用调试模式
    disableDebug() {
        this.debugMode = false;
        console.log('🔍 语音识别调试模式已禁用');
    }

    // 记录调试信息
    log(message: string, data?: any) {
        if (this.debugMode) {
            console.log(`🔍 [语音调试] ${message}`, data || '');
        }
    }

    // 记录错误信息
    error(message: string, error?: any) {
        if (this.debugMode) {
            console.error(`🔍 [语音调试] ❌ ${message}`, error || '');
        }
    }

    // 记录成功信息
    success(message: string, data?: any) {
        if (this.debugMode) {
            console.log(`🔍 [语音调试] ✅ ${message}`, data || '');
        }
    }

    // 记录警告信息
    warn(message: string, data?: any) {
        if (this.debugMode) {
            console.warn(`🔍 [语音调试] ⚠️ ${message}`, data || '');
        }
    }

    // 检查浏览器兼容性
    checkBrowserCompatibility() {
        const checks = {
            webSpeechAPI: 'webkitSpeechRecognition' in window || 'SpeechRecognition' in window,
            webSocket: 'WebSocket' in window,
            mediaDevices: 'mediaDevices' in navigator,
            getUserMedia: 'getUserMedia' in navigator.mediaDevices,
            audioContext: 'AudioContext' in window || 'webkitAudioContext' in window,
            crypto: 'crypto' in window && 'subtle' in window.crypto
        };

        this.log('浏览器兼容性检查', checks);

        const issues = Object.entries(checks)
            .filter(([key, supported]) => !supported)
            .map(([key]) => key);

        if (issues.length > 0) {
            this.warn('浏览器兼容性问题', issues);
        } else {
            this.success('浏览器完全兼容');
        }

        return { checks, issues };
    }

    // 检查网络连接
    async checkNetworkConnection() {
        try {
            const response = await fetch('https://iat-api.xfyun.cn', {
                method: 'HEAD',
                mode: 'no-cors'
            });
            this.success('网络连接正常');
            return true;
        } catch (error) {
            this.error('网络连接失败', error);
            return false;
        }
    }

    // 检查麦克风权限
    async checkMicrophonePermission() {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            this.success('麦克风权限正常');
            stream.getTracks().forEach(track => track.stop());
            return true;
        } catch (error) {
            this.error('麦克风权限被拒绝', error);
            return false;
        }
    }

    // 测试WebSocket连接
    testWebSocketConnection(url: string): Promise<boolean> {
        return new Promise((resolve) => {
            const ws = new WebSocket(url);
            const timeout = setTimeout(() => {
                ws.close();
                this.error('WebSocket连接超时');
                resolve(false);
            }, 5000);

            ws.onopen = () => {
                clearTimeout(timeout);
                this.success('WebSocket连接成功', { url });
                ws.close();
                resolve(true);
            };

            ws.onerror = (error) => {
                clearTimeout(timeout);
                this.error('WebSocket连接失败', { url, error });
                resolve(false);
            };

            ws.onclose = (event) => {
                clearTimeout(timeout);
                this.log('WebSocket连接关闭', { code: event.code, reason: event.reason });
            };
        });
    }

    // 生成诊断报告
    async generateDiagnosticReport() {
        this.log('开始生成诊断报告...');

        const report = {
            timestamp: new Date().toISOString(),
            browser: {
                userAgent: navigator.userAgent,
                language: navigator.language,
                platform: navigator.platform
            },
            compatibility: this.checkBrowserCompatibility(),
            network: await this.checkNetworkConnection(),
            microphone: await this.checkMicrophonePermission(),
            websocket: await this.testWebSocketConnection('wss://iat-api.xfyun.cn/v2/iat')
        };

        this.log('诊断报告生成完成', report);
        return report;
    }

    // 打印诊断报告
    printDiagnosticReport() {
        this.generateDiagnosticReport().then(report => {
            console.group('🔍 语音识别诊断报告');
            console.log('时间:', report.timestamp);
            console.log('浏览器:', report.browser);
            console.log('兼容性:', report.compatibility);
            console.log('网络:', report.network ? '✅ 正常' : '❌ 异常');
            console.log('麦克风:', report.microphone ? '✅ 正常' : '❌ 异常');
            console.log('WebSocket:', report.websocket ? '✅ 正常' : '❌ 异常');
            console.groupEnd();
        });
    }
}

// 导出单例实例
export const voiceDebugger = VoiceDebugger.getInstance();

// 在开发环境下自动启用调试模式
if (process.env.NODE_ENV === 'development') {
    voiceDebugger.enableDebug();
}

